package cn.imokay;

import cn.imokay.entity.Author;
import org.junit.Before;
import org.junit.Test;

import java.util.List;
import java.util.Optional;
import java.util.function.Function;

public class OptionalDemo {
    List<Author> authors;
    Author auth ;

    @Before
    public void getAuthors() {
        System.out.println("初始化数据");
        authors = Author.getAuthors();
        auth = authors.get(0);
    }

    @Test
    public void newOptionalObjTest1() {
        //访空指针
        Optional<Object> o = Optional.ofNullable(null);
        o.ifPresent(a->System.out.println(a.toString()));
        Object o1 = o.get();
    }

    @Test
    public void newOptionalObjTest2() {
        //确定对象不是空的时候
        Optional<Object> o = Optional.of(null);
        o.ifPresent(o1 -> System.out.println(o1));
        Object o1 = o.get();
    }

    @Test
    public void optionalObjGetTest3() {
        //访空指针
        Optional<Author> o = Optional.ofNullable(null);
        o.ifPresent(a->System.out.println(a.toString()));
        //直接get,如果没有对象会直接跑错
        //Author o1 = o.get();
        //推荐下卖弄这样获取
        Author author2 = o.orElseGet(() -> new Author().setName("sdhgksd"));
        System.out.println(author2.toString());
    }

    @Test
    public void optionalObjGetTest4() {
        //访空指针
        Optional<Author> o = Optional.ofNullable(null);
        o.ifPresent(a->System.out.println(a.toString()));
        //直接get,如果没有对象会直接跑错
        //Author o1 = o.get();
        //入轨没有数，手动跑异常
        o.orElseThrow(()-> new RuntimeException("null值"));
    }

    @Test
    public void optionalFilterTest() {
        Optional<Author> o = Optional.ofNullable(auth);

        o.ifPresent(a->System.out.println(a.toString()));

        Optional<Author> optionalAuthor = o.filter(author -> author.getAge() > 18);
        optionalAuthor.ifPresent(a->System.out.println(a.toString()));

        optionalAuthor.orElseThrow(() -> new RuntimeException("空对象"));

    }

    @Test
    public void optionalPresentTest() {
        Optional<Author> auth1 = Optional.ofNullable(auth);
        auth1.ifPresent(a -> System.out.println(a.toString()));

        boolean present = auth1.isPresent();

    }

    @Test
    public void optionalMapTest() {
        Optional<Author> o = Optional.ofNullable(auth);
        o.map(Author::getBooks)
                .ifPresent( books -> System.out.println(books.toString()));
    }

}
